package com.csu.servlet;

import com.csu.entiry.User;
import com.csu.service.UserService;
import com.csu.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "RegisterServlet", value = "/RegisterServlet")
public class RegisterServlet extends HttpServlet {

    private final UserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("registerUsername");
        String password = request.getParameter("registerPassword");
        String repeatedPassword = request.getParameter("registerRepeatedPassword");

        try {
            String msg = userService.Register(username, password, repeatedPassword);
            System.out.println(username);
            System.out.println(msg);
            response.setContentType("text/plain");
            PrintWriter out = response.getWriter();
            out.println(msg);
        } catch (RuntimeException e) {
            String errorMessage = e.getMessage();
            System.out.println("Exception in RegisterServlet: " + errorMessage);
            request.setAttribute("errorMessage", errorMessage);
        }
    }
}
